package com.xuecheng.controller;

import com.alibaba.nacos.common.http.param.MediaType;
import com.xuecheng.dto.QueryMediaParamsDTO;
import com.xuecheng.dto.UploadFileParamsDTO;
import com.xuecheng.exception.XueChengPlusException;
import com.xuecheng.model.PageParams;
import com.xuecheng.model.PageResult;
import com.xuecheng.model.RestResponse;
import com.xuecheng.po.MediaFiles;
import com.xuecheng.service.MediaFileService;
import com.xuecheng.vo.UploadFileResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 媒资文件管理接口
 */
@Slf4j
@Api(value = "媒资文件管理接口", tags = "媒资文件管理接口")
@RestController
public class MediaFilesController {
	
	@Resource
	private MediaFileService mediaFileService;
	
	@ApiOperation("媒资列表查询接口")
	@PostMapping("/files")
	public PageResult<MediaFiles> list(PageParams pageParams, @RequestBody QueryMediaParamsDTO queryMediaParamsDTO) {
		Long companyId = 1232141425L;
		log.info("pageParams:{}, queryMediaParamsDTO:{}", pageParams, queryMediaParamsDTO);
		return mediaFileService.queryMediaFiels(companyId, pageParams, queryMediaParamsDTO);
		
	}
	
	@RequestMapping(value = "/upload/coursefile", consumes = {MediaType.MULTIPART_FORM_DATA})
	public UploadFileResultVO upload(@RequestPart("filedata") MultipartFile filedata,
	                                 @RequestParam(value = "folder", required = false) String folder,
	                                 @RequestParam(value = "objectName", required = false) String objectName) {
		Long companyId = 1232141425L;
		UploadFileParamsDTO uploadFileParamsDTO = new UploadFileParamsDTO();
		String contentType = filedata.getContentType();
		uploadFileParamsDTO.setContentType(contentType);
		uploadFileParamsDTO.setFileSize(filedata.getSize());//文件大小
		if (contentType.indexOf("image") >= 0) {
			//是个图片
			uploadFileParamsDTO.setFileType("001001");
		} else {
			uploadFileParamsDTO.setFileType("001003");
		}
		uploadFileParamsDTO.setFilename(filedata.getOriginalFilename());//文件名称
		UploadFileResultVO uploadFileResultVO = null;
		try {
			uploadFileResultVO = mediaFileService.uploadFile(companyId, filedata.getBytes(), uploadFileParamsDTO,
				folder, objectName);
		} catch (Exception e) {
			XueChengPlusException.cast("上传文件过程中出错");
		}
		return uploadFileResultVO;
	}
	
	@ApiOperation("预览文件")
	@GetMapping("/preview/{mediaId}")
	public RestResponse<String> getPlayUrlByMediaId(@PathVariable String mediaId) {
		
		//调用service查询文件的url
		
		MediaFiles mediaFiles = mediaFileService.getFileById(mediaId);
		return RestResponse.success(mediaFiles.getUrl());
	}
}
